//
//  MovieViewTableController.m
//  CMS
//
//  Created by Vuong Van Khanh on 12/10/12.
//  Copyright (c) 2012 Rikkei. All rights reserved.
//

#import "MovieViewTableController.h"
#import "MovieViewCellController.h"
#import "MoviePlayer.h"
#import <MediaPlayer/MediaPlayer.h>

@implementation MovieViewTableController
@synthesize tableData;

- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    
    [alertView show];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //hide TableViewCell borber
    self.tableView.separatorColor = [UIColor clearColor];
    
    NSArray *moviePaths = nil;
	NSBundle *bundle = [NSBundle mainBundle];
	if (bundle) 
	{
        //		NSString *moviePath = [bundle pathForResource:@"Movie" ofType:@"m4v"];
        moviePaths = [[NSBundle mainBundle] pathsForResourcesOfType:@"m4v" inDirectory:nil]; 
        //        NSInteger numberOfMovies = [moviePaths count];
        
	}
    tableData = [[NSMutableArray alloc] init];
    NSInteger numberOfItems = [moviePaths count];
	for (int i = 0; i < numberOfItems; i++)
	{
		[tableData addObject:[moviePaths objectAtIndex:i]];
	}
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return YES;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSInteger rowCount = [tableData count]%2?[tableData count]/2 + 1:[tableData count]/2;
    return rowCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MovieCell";
    
    MovieViewCellController *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[MovieViewCellController alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    NSURL *moviePath1 = [NSURL fileURLWithPath:[tableData objectAtIndex:[indexPath row] * 2]];
    int path2 = [indexPath row] * 2 + 1;
    NSURL *moviePath2 = nil;
    if(path2 <= [tableData count] - 1)
    {
        moviePath2 = [NSURL fileURLWithPath:[tableData objectAtIndex:path2]];
    }
    
    if (moviePath1)
    {
        MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:moviePath1];
        UIImage *thumb = [player thumbnailImageAtTime:player.duration/10.0 timeOption:MPMovieTimeOptionNearestKeyFrame];        
        NSString *fileName = [moviePath1 lastPathComponent];
        [cell.button1 setBackgroundImage:thumb forState:UIControlStateNormal];
        [cell.label1 setText:fileName];
        url1 = moviePath1;
        [cell.button1 addTarget:self action:@selector(button1Clicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    if (moviePath2)
    {
        MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:moviePath2];
        UIImage *thumb = [player thumbnailImageAtTime:player.duration/10.0 timeOption:MPMovieTimeOptionNearestKeyFrame];        
        NSString *fileName = [moviePath2 lastPathComponent];
        [cell.button2 setBackgroundImage:thumb forState:UIControlStateNormal];
        [cell.label2 setText:fileName];
        url2 = moviePath2;
        [cell.button2 addTarget:self action:@selector(button2Clicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    //set view hide when no data
    if([indexPath row] == [indexPath length] - 1 && [tableData count] %2)
    {
        [cell.button2 setHidden:YES];
        [cell.label2 setHidden:YES];
    }
    //clear selection color when touch on TableViewCell background
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
//    MovieViewCellController *cell =(MovieViewCellController *)[self.tableView cellForRowAtIndexPath:indexPath];
//    NSLog(@"didSelectRowAtIndexPath: %@", indexPath.row);
    
}

- (IBAction)button1Clicked:(id)sender {
    MoviePlayer *moviePlayer = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil] instantiateViewControllerWithIdentifier:@"MoviePlayer"];
    moviePlayer.url = url1;

    if(url1)
        [self.navigationController pushViewController:moviePlayer animated:YES];
    else
        [self alertStatus:@"Movie not exits, please download again!" :@"Error"];
    
}

- (IBAction)button2Clicked:(id)sender {


    MoviePlayer *moviePlayer = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil] instantiateViewControllerWithIdentifier:@"MoviePlayer"];
    moviePlayer.url = url2;

    if(url2)
        [self.navigationController pushViewController:moviePlayer animated:YES];
    else
        [self alertStatus:@"Movie not exits, please download again!" :@"Error"];
        
}
@end
